<template>
  <div class="search-form">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      :inline="true"
      label-width="auto">
      <el-form-item
        label="userId尾号"
        prop="userIdEnd">
        <el-select-v2
          placeholder="请选择"
          multiple
          collapse-tags
          collapse-tags-tooltip
          v-model="ruleForm.userIdEnd"
          @blur="formChangeEvent.userIdEndChange"
          :options="options" />
      </el-form-item>
      <el-form-item
        label="时间周期"
        prop="intervalType">
        <el-select
          placeholder="请选择"
          v-model="ruleForm.intervalType"
          @change="formChangeEvent.intervalTypeChange">
          <el-option
            v-for="(label, value) in intervalTypeOptionsMap"
            :key="value"
            :label="label"
            :value="value" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-show="+ruleForm.intervalType !== 1"
        label="日期"
        prop="date">
        <el-date-picker
          v-model="ruleForm.date"
          value-format="YYYY-MM-DD"
          placeholder="请选择"
          type="date"
          :disabled-date="disabledDate"
          @change="formChangeEvent.dateChange" />
      </el-form-item>
      <el-form-item
        v-show="+ruleForm.intervalType !== 1"
        label="对照日期"
        prop="comparisonDate">
        <el-date-picker
          v-model="ruleForm.comparisonDate"
          value-format="YYYY-MM-DD"
          placeholder="请选择"
          type="date"
          :disabled-date="disabledDate"
          @change="formChangeEvent.dateChange" />
      </el-form-item>
      <el-form-item>
        <!-- <el-button
          type="primary"
          plain
          @click="getPreviewData">
          查询
        </el-button> -->
        <el-button
          class="search-btn"
          type="primary"
          success
          plain
          @click="$router.push({ path: '/exposureContrast' })">
          前往对照
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, defineEmits, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { fetchExposureLinerData } from '@/api/exposureLine'
import { useExposureLineStore } from '@/stores/exposureLine'
import { intervalTypeOptionsMap } from '@/maps/intervalType'

const exposureLineStore = useExposureLineStore()

interface RuleForm {
  userIdEnd: []
  intervalType: string
  date: string
  comparisonDate: string
}
const today = new Date()
const yesterday = new Date(today)
yesterday.setDate(yesterday.getDate() - 1)

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  userIdEnd: [],
  intervalType: '1',
  date: today.toISOString().substring(0, 10),
  comparisonDate: yesterday.toISOString().substring(0, 10),
})

const rules = reactive<FormRules<RuleForm>>({
  userIdEnd: [{ required: false, trigger: 'blur' }],
  intervalType: [
    {
      required: false,
      trigger: 'change',
    },
  ],
  date: [
    {
      type: 'date',
      required: false,
      trigger: 'change',
    },
  ],
  comparisonDate: [
    {
      type: 'date',
      required: false,
      trigger: 'change',
    },
  ],
})

const options = Array.from({ length: 10 }).map((_, idx) => ({
  value: idx,
  label: idx,
}))
const emit = defineEmits(['query-change'])

/**
 * 注册表单事件
 */
const formChangeEvent = {
  /**
   * 用户ID改变事件
   */
  userIdEndChange() {
    getPreviewData()
  },
  /**
   * 时间周期修改事件
   */
  intervalTypeChange() {
    exposureLineStore.setIntervalType(ruleForm.intervalType)
    const yesterday = new Date(ruleForm.date)
    yesterday.setDate(yesterday.getDate() - 1)
    ruleForm.comparisonDate = yesterday.toISOString().substring(0, 10)
    getPreviewData()
  },
  /**
   * 日期改变事件
   */
  dateChange(date: string) {
    const yesterday = new Date(date)
    yesterday.setDate(yesterday.getDate() - 1)
    ruleForm.comparisonDate = yesterday.toISOString().substring(0, 10)
    getPreviewData()
  },
}

/**
 * 获取预览数据
 */
const getPreviewData = async () => {
  exposureLineStore.setLoading(true)
  const result = await fetchExposureLinerData({
    ...ruleForm,
    userIdEnd: ruleForm.userIdEnd.join(','),
  })
  exposureLineStore.setLoading(false)
  exposureLineStore.setPreviewData(result.data)
  emit('query-change', ruleForm)
}

/**
 * 禁用日期
 */
const disabledDate = (time: Date) => {
  // 获取当前日期（不含时间部分）
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  // 获取明天的日期
  const tomorrow = new Date(today)
  tomorrow.setDate(today.getDate() + 1)

  // 禁用明天及之后的日期
  return time.getTime() >= tomorrow.getTime()
}

onMounted(() => {
  getPreviewData()
})
</script>
<style scoped lang="scss">
.el-form-item {
  margin-right: 0;
}
:deep(.el-form-item__content) {
  min-width: 100px;
}
.search-btn {
  margin-left: 10px;
}
</style>
